package com.example.demo.util;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class RandomUtil {

    public static String randomNum(int size){
        StringBuilder sb = new StringBuilder(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 生成值介于区间[min, max],长度为 length的随机数，不足长度的，在前面补0
     * @param min
     * @param max
     * @param length
     * @return
     */
    public static String randomNum(int min, int max, int length){
        ThreadLocalRandom tr = ThreadLocalRandom.current();
        int random = tr.nextInt(max - min + 1) + min;
        String randomStr = String.valueOf(random);
        if (randomStr.length() > length) {
            randomStr = randomStr.substring(0, 6);
        } else {
            randomStr = StringUtils.leftPad(randomStr, length, "0");
        }
        return randomStr;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(randomNum(1, 99999999, 6));
            try {
                Thread.sleep(100l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
